package com.example.filemanager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import android.os.Environment;

public class FileType {

	public static int checkFileType(String filePath) {
		// 文件类型代码
		String filecode = "";
		// 文件类型
		String fileType = "";
		int typePNG = R.drawable.unkown;
		try {
			// 从SDCARD下读取一个文件
			// FileInputStream inputStream = new FileInputStream(Environment
			// .getExternalStorageDirectory().getAbsolutePath()
			// + "camera.jpg");
			FileInputStream inputStream = new FileInputStream(filePath);
			byte[] buffer = new byte[2];

			// 通过读取出来的前两个字节来判断文件类型
			if (inputStream.read(buffer) != -1) {
				for (int i = 0; i < buffer.length; i++) {
					// 获取每个字节与0xFF进行与运算来获取高位，这个读取出来的数据不是出现负数
					// 并转换成字符串
					filecode += Integer.toString((buffer[i] & 0xFF));

				}
				
				//打印不同类型文件的文件类型代码
				if ((new File(filePath)).isDirectory()) {

				} else {
					String type = filePath.substring(filePath.length() - 4,
							filePath.length());
					System.out.println("type: " + type + ";  " + "filecode:  "
							+ filecode);
				}
				// 把字符串再转换成Integer进行类型判断
				switch (Integer.parseInt(filecode)) {
				case 7790:
					// fileType = "exe";
					fileType = "unknown";
					typePNG = R.drawable.unkown;
					break;
				case 7784:
					 fileType = "midi";
//					fileType = "mp3";
					typePNG = R.drawable.mid;
					break;
				case 8297:
					fileType = "rar";
					typePNG = R.drawable.rar;
					break;
				case 8075:
					fileType = "zip";
					typePNG = R.drawable.zip;
					break;
				case 255216:
					fileType = "jpg";
					typePNG = R.drawable.jpg;
					break;
				case 7173:
					// fileType = "gif";
					fileType = "jpg";
					typePNG = R.drawable.jpg;
					break;
				case 6677:
					// fileType = "bmp";
					fileType = "jpg";
					typePNG = R.drawable.jpg;
					break;
				case 13780:
					fileType = "png";
					typePNG = R.drawable.png;
					break;
				case 5450://.txt
					typePNG = R.drawable.paper;
					break;
				case 8381://.db
					typePNG = R.drawable.paper;
					break;
//				case 6063://.xml
//
//					break;
				default:
					// fileType = "unknown type: " + filecode;
					fileType = "unkown";
					typePNG = R.drawable.unkown;
				}

			}
			System.out.println(fileType);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return typePNG;

	}
}
